<!--
  ~ Copyright 2017 Okta, Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Okta Sign-in-widget + jQuery Example</title>

    <base href="/">

    <script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.13.0/js/okta-sign-in.min.js" type="text/javascript"></script>
    <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.13.0/css/okta-sign-in.min.css" type="text/css" rel="stylesheet">
    <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.13.0/css/okta-theme.css" type="text/css" rel="stylesheet">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<body>
<!-- Render the login widget here -->
<div id="okta-login-container"></div>

<!-- Render the REST response here -->
<div id="cool-stuff-here"></div>

<!-- And a logout button, hidden by default -->
<button id="logout" type="button" class="btn btn-danger" style="display:none">Logout</button>

<script>

  $.ajax({
    url: "/sign-in-widget-config",
  }).then(function(data) {

    // we are priming our config object with data retrieved from the server in order to make this example easier to run
    // You could statically define your config like if you wanted too:
    /*
    const data = {
      baseUrl: 'https://dev-123456.oktapreview.com',
      clientId: '00icu81200icu812w0h7',
      redirectUri: 'http://localhost:8080',
      authParams: {
        issuer: 'https://dev-123456.oktapreview.com/oauth2/ausar5cbq5TR00icu812',
        responseType: ['id_token', 'token']
      }
    }; */

    // we want the access token so include 'token'
    data.authParams.responseType = ['id_token', 'token'];
    data.redirectUri = window.location.href; // simple single page app
    data.logo = 'https://ok1static.oktacdn.com/assets/img/logos/okta-logo.png';

    // setup the widget
    window.oktaSignIn = new OktaSignIn(data);

    // handle the rest of the page
    doInit();
  });

  /**
   * Makes a request to a REST resource and displays a simple message to the page.
   * @param accessToken The access token used for the auth header
   */
  function doAllTheThings(accessToken) {

    // include the Bearer token in the request
    $.ajax({
      url: "/welcome",
      headers: {
        'Authorization': "Bearer " + accessToken
      },
    }).then(function(data) {
      // Render the message of the day
      $('#cool-stuff-here').append(data.messageOfTheDay + "<br><strong>User:</strong> " + data.username);
    });

    // show the logout button
    $( "#logout" )[0].style.display = 'block';
  }

  function doInit() {

    $( "#logout" ).click(function() {
      oktaSignIn.signOut(() => {
        oktaSignIn.tokenManager.clear();
        location.reload();
      });
    });

    // Check if we already have an access token
    const token = oktaSignIn.tokenManager.get('my_access_token');

    // if we do great, just go with it!
    if (token) {
      doAllTheThings(token.accessToken)
    } else {

      // otherwise show the login widget
      oktaSignIn.renderEl(
        {el: '#okta-login-container'},
        function (response) {

          // check if success
          if (response.status === 'SUCCESS') {

            // for our example we have the id token and the access token
            oktaSignIn.tokenManager.add('my_id_token', response[0]);
            oktaSignIn.tokenManager.add('my_access_token', response[1]);

            // hide the widget
            oktaSignIn.hide();

            // now for the fun part!
            doAllTheThings(response[1].accessToken);
          }
        },
        function (err) {
          // handle any errors
          console.log(err);
        }
      );
    }
  }

</script>
</body>
</html>
